package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.port.fee.common.Result;
import com.port.fee.dto.CargoDTO;
import com.port.fee.entity.Cargo;
import com.port.fee.service.CargoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 货物管理控制器
 */
@RestController
@RequestMapping("/cargo")
@Tag(name = "货物管理", description = "货物相关接口")
public class CargoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CargoController.class);

    @Autowired
    private CargoService cargoService;

    /**
     * 分页查询货物列表
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询货物列表", description = "根据条件分页查询货物列表")
    public Result<Map<String, Object>> list(@RequestBody CargoDTO cargoDTO) {
        // 转换对象
        Cargo cargo = new Cargo();
        BeanUtils.copyProperties(cargoDTO, cargo);

        // 默认值处理
        int pageNum = cargoDTO.getPageNum() == null ? 1 : cargoDTO.getPageNum();
        int pageSize = cargoDTO.getPageSize() == null ? 10 : cargoDTO.getPageSize();

        // 分页查询
        Page<Cargo> page = cargoService.listCargos(cargo, pageNum, pageSize);

        // 封装返回结果
        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("pages", page.getPages());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());

        return Result.success(data);
    }

    /**
     * 获取货物详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取货物详情", description = "根据货物ID获取详情")
    public Result<Cargo> getInfo(@PathVariable("id") Long id) {
        Cargo cargo = cargoService.getCargoById(id);
        if (cargo != null) {
            return Result.success(cargo);
        } else {
            return Result.failed("货物不存在");
        }
    }

    /**
     * 新增货物
     */
    @PostMapping
    @Operation(summary = "新增货物", description = "新增货物信息")
    public Result<Void> add(@RequestBody CargoDTO cargoDTO) {
        try {
            LOGGER.info("添加货物请求参数: {}", cargoDTO);

            // 验证必要参数
            if (cargoDTO.getCustomerId() == null) {
                return Result.failed("客户ID不能为空");
            }

            if (cargoDTO.getCargoName() == null || cargoDTO.getCargoName().trim().isEmpty()) {
                return Result.failed("货物名称不能为空");
            }

            if (cargoDTO.getCargoType() == null || cargoDTO.getCargoType().trim().isEmpty()) {
                return Result.failed("货物类型不能为空");
            }

            if (cargoDTO.getQuantity() == null) {
                return Result.failed("数量不能为空");
            }

            if (cargoDTO.getUnit() == null || cargoDTO.getUnit().trim().isEmpty()) {
                return Result.failed("计量单位不能为空");
            }

            if (cargoDTO.getEntryTime() == null) {
                return Result.failed("进港时间不能为空");
            }

            Cargo cargo = new Cargo();
            BeanUtils.copyProperties(cargoDTO, cargo);

            // 设置默认值
            if (cargo.getStatus() == null) {
                cargo.setStatus(1); // 默认在港状态
            }

            cargo.setCreateTime(new Date());
            cargo.setUpdateTime(new Date());

            LOGGER.info("准备保存货物信息: {}", cargo);

            if (cargoService.addCargo(cargo)) {
                return Result.success(null, "新增成功");
            } else {
                return Result.failed("新增失败");
            }
        } catch (Exception e) {
            LOGGER.error("添加货物异常: ", e);
            return Result.failed("添加货物失败: " + e.getMessage());
        }
    }

    /**
     * 修改货物
     */
    @PutMapping
    @Operation(summary = "修改货物", description = "修改货物信息")
    public Result<Void> update(@RequestBody CargoDTO cargoDTO) {
        if (cargoDTO.getCargoId() == null) {
            return Result.failed("货物ID不能为空");
        }

        Cargo cargo = new Cargo();
        BeanUtils.copyProperties(cargoDTO, cargo);

        if (cargoService.updateCargo(cargo)) {
            return Result.success(null, "修改成功");
        } else {
            return Result.failed("修改失败");
        }
    }

    /**
     * 删除货物
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除货物", description = "根据ID删除货物")
    public Result<Void> delete(@PathVariable("id") Long id) {
        if (cargoService.deleteCargo(id)) {
            return Result.success(null, "删除成功");
        } else {
            return Result.failed("删除失败");
        }
    }

    /**
     * 货物出港
     */
    @PutMapping("/exit/{id}")
    @Operation(summary = "货物出港", description = "设置货物出港状态")
    public Result<Void> exitPort(
            @PathVariable("id") Long id,
            @Parameter(description = "出港时间，为空则使用当前时间") @RequestParam(required = false) String exitTimeStr) {

        try {
            // 如果出港时间为空，则使用当前时间
            Date exitTime;
            if (exitTimeStr == null || exitTimeStr.trim().isEmpty()) {
                exitTime = new Date();
            } else {
                try {
                    // 尝试解析ISO格式日期字符串
                    exitTime = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(exitTimeStr);
                } catch (Exception e) {
                    try {
                        // 尝试解析标准日期格式
                        exitTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(exitTimeStr);
                    } catch (Exception e2) {
                        LOGGER.error("解析日期失败: {}", exitTimeStr, e2);
                        return Result.failed("日期格式错误，请使用yyyy-MM-dd'T'HH:mm:ss.SSS'Z'或yyyy-MM-dd HH:mm:ss格式");
                    }
                }
            }

            if (cargoService.exitPort(id, exitTime)) {
                return Result.success(null, "出港操作成功");
            } else {
                return Result.failed("出港操作失败");
            }
        } catch (Exception e) {
            LOGGER.error("货物出港异常: ", e);
            return Result.failed("货物出港失败: " + e.getMessage());
        }
    }
}